package com.sskj.bibi.presenter;

import com.google.gson.Gson;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.sskj.bibi.bean.CoinFee;
import com.sskj.bibi.bean.rxbus.CoinUpdateBean;
import com.sskj.bibi.http.HttpConfig;
import com.sskj.bibi.ui.fragment.BibiBuyAndSellFragment;
import com.sskj.common.base.HttpData;
import com.sskj.common.http.WebSocketObserver;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.http.JsonCallBack;
import com.sskj.lib.http.JsonConverter;
import com.sskj.lib.util.CommonUtil;
import com.sskj.lib.util.ExceptionUtil;

import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class BibiBuyAndSellFragmentPresenter extends BasePresenter<BibiBuyAndSellFragment> {
    private Disposable disposable;
    private String code;

    /**
     * 提交订单
     *
     * @param code          币种编号
     * @param price         委托价格 （限价必填）
     * @param num           委托数量 （限价必填）
     * @param tradeType     1买入 2卖出 （必填）
     * @param billPriceType 1市价 2限价 （必填）
     */
    public void submit(String code, String price, String num,
                       String tradeType, String billPriceType) {

        httpService.createCoinOrder(code, price, num, tradeType, billPriceType)
                .tag(this)
                .execute(new JsonCallBack<HttpData>(this) {
                    @Override
                    public void onSuccess(Response<HttpData> response) {
                        HttpData httpData = response.body();
                        ToastUtil.showShort(httpData.getMsg());
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.buySuccess();
                        }
                    }
                });
    }

    public void getCoinInfo(String code, UserData userData) {
        if (userData != null) {
            Flowable<HttpData<List<CoinBean>>> flowCoin = httpService.getProduct(null, code)
                    .converter(new JsonConverter<HttpData<List<CoinBean>>>() {
                    })
                    .adapt(new FlowableBody<>());

            Flowable<HttpData<CoinFee>> flowCoinFeeInfo = httpService.getCoinFee(code)
                    .converter(new JsonConverter<HttpData<CoinFee>>() {
                    })
                    .adapt(new FlowableBody<>());
            disposable = Flowable.zip(flowCoin, flowCoinFeeInfo,
                    (listHttpData, coinFeeHttpData) -> {
                        CoinUpdateBean coinUpdateBean = new CoinUpdateBean();
                        coinUpdateBean.setCoinMoney(coinFeeHttpData.getData().getLeft_code());
                        coinUpdateBean.setUsdtMoney(coinFeeHttpData.getData().getRight_code());
                        coinUpdateBean.setCoinType(listHttpData.getData().get(0).getName());
                        coinUpdateBean.setMarketPrice(listHttpData.getData().get(0).getPrice());
                        coinUpdateBean.setFee(coinFeeHttpData.getData().getTrans_fee());
                        return coinUpdateBean;
                    }).subscribe(stockCoin -> mView.updateCoinData(stockCoin), ExceptionUtil::dealException);
        } else {
            httpService.getProduct(null, code)
                    .tag(this)
                    .execute(new JsonCallBack<HttpData<List<CoinBean>>>() {
                        @Override
                        public void onSuccess(Response<HttpData<List<CoinBean>>> response) {
                            HttpData<List<CoinBean>> httpData = response.body();
                            if (httpData.getStatus() == HttpConfig.OK) {
                                if (httpData.getData() != null && httpData.getData().size() > 0) {
                                    CoinBean productBean = httpData.getData().get(0);
                                    CoinUpdateBean coinUpdateBean = new CoinUpdateBean();
                                    coinUpdateBean.setCoinMoney("0");
                                    coinUpdateBean.setUsdtMoney("0");
                                    coinUpdateBean.setCoinType(productBean.getCode());
                                    coinUpdateBean.setMarketPrice(productBean.getPrice());
                                    coinUpdateBean.setFee("0");
                                    mView.updateCoinData(coinUpdateBean);
                                }
                            }
                        }
                    });
        }
    }

    //把注释去掉
    public void getDepthData(String code) {
        httpService.getDeepData(code)
                .execute(new JsonCallBack<HttpData<WSFiveBean>>() {
                    @Override
                    public void onSuccess(Response<HttpData<WSFiveBean>> response) {
                        HttpData<WSFiveBean> httpData = response.body();
                        if (httpData.getStatus() == HttpConfig.OK) {
                            mView.updateDeep(httpData.getData());
                        }
                    }
                });
    }


    @Override
    public void detachView() {
        DisposUtil.close(disposable);
        super.detachView();
    }


    private WebSocketObserver stockSocket;
    private Disposable stockDisposable;


    public void initSocket(String code) {
        if (code==null)
            return;
        code= CommonUtil.dealReuqestCode(code);
        if (stockSocket == null) {
            stockSocket = httpService.pushCoinFiveDeep(code);
            stockDisposable = stockSocket
                    .map(s -> new Gson().fromJson(s, WSFiveBean.class))
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(data -> mView.updateDeep(data), e -> {

                    });
        } else {
//            stockSocket.send("{\"unsub\":\"pct." + this.code + "\"}");
            stockSocket.send("{\"type\":\"depth_list\",\"list\":[\""+code+"\"]}");
        }
        this.code = code;
    }

    public void sendCode(String code) {

        initSocket(code);
    }

    public void closeWebSocket() {
        stockSocket.close();
        stockSocket = null;

    }

}
